// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2021 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------

export default {// 设置选中的方法
// 记忆选择核心方法
  changePageCoreRecordData: function(multipleSelectionAll, multipleSelection, tableData, successFn) {
    // 标识当前行的唯一键的名称
    const idKey = 'uid'
    const that = this
    // 如果总记忆中还没有选择的数据，那么就直接取当前页选中的数据，不需要后面一系列计算
    if (multipleSelectionAll.length <= 0) {
      multipleSelectionAll = multipleSelection
      successFn(multipleSelectionAll)
      return
    }
    // 总选择里面的key集合
    const selectAllIds = []
    multipleSelectionAll.forEach(row => {
      selectAllIds.push(row[idKey])
    })
    const selectIds = []
    // 获取当前页选中的id
    multipleSelection.forEach(row => {
      selectIds.push(row[idKey])
      // 如果总选择里面不包含当前页选中的数据，那么就加入到总选择集合里
      if (selectAllIds.indexOf(row[idKey]) < 0) {
        multipleSelectionAll.push(row)
      }
    })
    const noSelectIds = []
    // 得到当前页没有选中的id
    tableData.forEach(row => {
      if (selectIds.indexOf(row[idKey]) < 0) {
        noSelectIds.push(row[idKey])
      }
    })
    noSelectIds.forEach(uid => {
      if (selectAllIds.indexOf(uid) >= 0) {
        for (let i = 0; i < multipleSelectionAll.length; i++) {
          if (multipleSelectionAll[i][idKey] == uid) {
            // 如果总选择中有未被选中的，那么就删除这条
            multipleSelectionAll.splice(i, 1)
            break
          }
        }
      }
    })
    successFn(multipleSelectionAll)
  }
}
export function exportTest(url,fileName)
{
  const link = document.createElement('a');
  link.download = fileName;
  link.href = process.env.VUE_APP_BASE_API + "/file" + url;

  // 将 link 元素添加到 DOM 中，以便后续点击下载
  document.body.appendChild(link);

  // 等待链接元素被添加到 DOM 中
  setTimeout(() => {
    // 触发点击事件以下载文件
    link.click();

    // 监听点击事件，在点击完成后移除链接元素
    link.addEventListener('click', () => {
      setTimeout(() => {
        document.body.removeChild(link);
      }, 100);
    });
  }, 10); // 增加了一个10毫秒的延迟
}
export function createFile(flow, fileName = '') {
  const blob = new Blob([flow])
  const blobUrl = window.URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.style.display = 'none'
  if (fileApplication[flow.type]) {
    const ext = fileApplication[flow.type] ? fileApplication[flow.type] : '*'
    a.download = fileName + '_' + getCurrentTime() + '.' + ext
    a.href = blobUrl
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    return true
  } else {
    return false
  }
}

const fileApplication = objectReduce({
  xls: 'application/vnd.ms-excel',
  xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  csv: 'text/csv',
  doc: 'application/msword',
  docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  pdf: 'application/pdf',
  ppt: 'application/vnd.ms-powerpoint',
  pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  png: 'image/png',
  gif: 'image/gif',
  jpeg: 'image/jpeg',
  jpg: 'image/jpeg',
  mp3: 'audio/mpeg',
  aac: 'audio/aac',
  html: 'text/html',
  css: 'text/css',
  js: 'text/javascript',
  json: 'application/json',
  abw: 'application/x-abiword',
  arc: 'application/x-freearc',
  avi: 'video/x-msvideo',
  azw: 'application/vnd.amazon.ebook',
  bin: 'application/octet-stream',
  sql: 'application/x-msdownload',
  bmp: 'image/bmp',
  bz: 'application/x-bzip',
  bz2: 'application/x-bzip2',
  csh: 'application/x-csh',
  eot: 'application/vnd.ms-fontobject',
  epub: 'application/epub+zip',
  htm: 'text/html',
  ico: 'image/vnd.microsoft.icon',
  ics: 'text/calendar',
  jar: 'application/java-archive',
  jsonld: 'application/ld+json',
  mid: 'audio/midi audio/x-midi',
  midi: 'audio/midi audio/x-midi',
  mjs: 'text/javascript',
  mpeg: 'video/mpeg',
  mpkg: 'application/vnd.apple.installer+xml',
  odp: 'application/vnd.oasis.opendocument.presentation',
  ods: 'application/vnd.oasis.opendocument.spreadsheet',
  odt: 'application/vnd.oasis.opendocument.text',
  oga: 'audio/ogg',
  ogv: 'video/ogg',
  ogx: 'application/ogg',
  otf: 'font/otf',
  rar: 'application/x-rar-compressed',
  rtf: 'application/rtf',
  sh: 'application/x-sh',
  svg: 'image/svg+xml',
  swf: 'application/x-shockwave-flash',
  tar: 'application/x-tar',
  tif: 'image/tiff',
  tiff: 'image/tiff',
  ttf: 'font/ttf',
  txt: 'text/plain',
  vsd: 'application/vnd.visio',
  wav: 'audio/wav',
  weba: 'audio/webm',
  webm: 'video/webm',
  webp: 'image/webp',
  woff: 'font/woff',
  woff2: 'font/woff2',
  xhtml: 'application/xhtml+xml',
  xml: 'text/xml',
  xul: 'application/vnd.mozilla.xul+xml',
  zip: 'application/zip'
})

function objectReduce(obj) {
  let data = {}
  Object.keys(obj).forEach((item, index) => {
    data[obj[item].toString()] = item
  })
  return data
}

export function getCurrentTime(fields = 's', time = null) {
  const date = time ? new Date(time) : new Date()
  let str = ''
  let y = date.getFullYear().toString()
  let m = (date.getMonth() + 1).toString()
  m = m.length == 1 ? '0' + m : m
  let d = date.getDate().toString()
  d = d.length == 1 ? '0' + d : d
  let h = date.getHours().toString()
  h = h.length == 1 ? '0' + h : h
  let i = date.getMinutes().toString()
  i = i.length == 1 ? '0' + i : i
  let s = date.getSeconds().toString()
  s = s.length == 1 ? '0' + s : s
  if (fields == 'y') {
    str = y
  }
  if (fields == 'm') {
    str = y + '-' + m
  }
  if (fields == 'd') {
    str = y + '-' + m + '-' + d
  }
  if (fields == 'h') {
    str = y + '-' + m + '-' + d + ' ' + h
  }
  if (fields == 'i') {
    str = y + '-' + m + '-' + d + ' ' + h + ':' + i
  }
  if (fields == 's') {
    str = y + '_' + m + '_' + d + '_' + h + i + s
  }
  return str
}

export function randomString(len) {
  len = len || 32
  var $chars = 'ABCDEFGHIJKLMNPPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789'
  var maxPos = $chars.length
  var pwd = ''
  for (let i = 0; i < len; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return pwd
}

export function findObjArray(data,key,value){
  for(let i=0;i<data.length;i++){
    let c=data[i];
    if(c[key]==value){
      return {index:i,value:c[key]};
    }
  }
  return false;
}

export function hasChild(data,child='childList',field='hasChild'){
  data.forEach(item=>{
    let text='';
    switch (item.menu_type){
      case 'M':
        text='顶级菜单';
        break;
      case 'C':
        text='次级菜单';
        break;
      case 'A':
        text='操作';
        break;
    }
    item.menu_type_text=text;
    if(item[child]&&item[child].length){
      item[field]=true;
      item[child]=hasChild(item[child]);
    }else{
      item[field]=false
    }
  })
  return data;
}

export function getForm(from,to){
  Object.keys(to).forEach(item=>{
    to[item]=from[item];
  })
}
